#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import argparse
import os
import shutil
import cantools.database

from CanFrameGenerator import CanFrame
from CanMessageGenerator import CanMessage
from Utils import toCamelCase

def ClearOutDirectory(path):
    if os.path.isdir(path) :
        shutil.rmtree(path)
    os.makedirs(path)

def GenerateCppSources(outDir, dbcFile):
    dbc = cantools.database.load_file(dbcFile)

    canFrameDir = outDir + "/CanFrames"
    os.makedirs(canFrameDir)

    canClassDir = outDir + "/CanMessage"
    os.makedirs(canClassDir)

    for message in dbc.messages :
        # if message.name == "CDU_OBC_3":
        #Generate CAN Frame
        GenerateCanFrameSources(canFrameDir, message)
        #Generate CAN Class
        GenerateCanMessageSources(canClassDir, message)

def GenerateCanFrameSources(outDir: str, message:cantools.database.Message):
    frame = CanFrame()
    frame.name = toCamelCase(message.name)
    frame.setLength(message.length)
    for singal in message.signals:
        frame.addSignal(singal)
    # frame.printBytes()

    headFileName = toCamelCase(message.name) + "Frame" + ".h"
    with open(outDir + "/" + headFileName, "w") as file:
        file.write(frame.outputCanFrameCode())

def GenerateCanMessageSources(canClassDir: str, message:cantools.database.Message):
    canMessage = CanMessage(message.name, toCamelCase(message.name))
    canMessage.initialize(message)
    canMessage.generateSource(canClassDir)

def main():
    parser = argparse.ArgumentParser(description='manual of this script')
    parser.add_argument("--dbc_file", type=str, default="", help= "Path of DBC")
    parser.add_argument("--out_dir", type=str, default="", help="Path of directory of generated c++ sources")
    args = parser.parse_args()

    ClearOutDirectory(args.out_dir)
    GenerateCppSources(args.out_dir, args.dbc_file)

if __name__ == "__main__" :
    main()
